package avicit.bdp.dms.oauth2;

import avicit.bdp.dms.oauth2.handler.ClientCredentialsTokenHandler;
import avicit.bdp.dms.oauth2.handler.RefreshTokenHandler;
import org.apache.oltu.oauth2.as.request.OAuthTokenRequest;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * TODO
 *
 * @author xugb
 * @date 2024/4/12 14:42
 */

public class OAuthTokenHandleDispatcher {
    private static final Logger LOG = LoggerFactory.getLogger(OAuthTokenHandleDispatcher.class);
    private List<OAuthTokenHandler> handlers = new ArrayList();
    private final OAuthTokenRequest tokenRequest;
    private final HttpServletResponse response;

    public OAuthTokenHandleDispatcher(OAuthTokenRequest tokenRequest, HttpServletResponse response) {
        this.tokenRequest = tokenRequest;
        this.response = response;
        this.initialHandlers();
    }

    private void initialHandlers() {
        this.handlers.add(new ClientCredentialsTokenHandler());
        this.handlers.add(new RefreshTokenHandler());
        LOG.debug("Initialed '{}' OAuthTokenHandler(s): {}", this.handlers.size(), this.handlers);
    }

    public void dispatch() throws OAuthProblemException, OAuthSystemException {
        Iterator var1 = this.handlers.iterator();

        OAuthTokenHandler handler;
        do {
            if (!var1.hasNext()) {
                throw new IllegalStateException("Not found 'OAuthTokenHandler' to handle OAuthTokenxRequest: " + this.tokenRequest);
            }

            handler = (OAuthTokenHandler)var1.next();
        } while(!handler.support(this.tokenRequest));

        LOG.debug("Found '{}' handle OAuthTokenxRequest: {}", handler, this.tokenRequest);
        handler.handle(this.tokenRequest, this.response);
    }
}
